package com.Logistics.pddispatch.init;

import com.Logistics.pddispatch.mapper.ScheduleJobMapper;
import com.Logistics.pddispatch.utils.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 项目启动时初始化定时任务
 */
@Component
@Slf4j
public class DispatchCommandLineRunner implements CommandLineRunner {
    @Autowired
    public Scheduler scheduler;
    @Autowired
    private ScheduleJobMapper scheduleJobMapper;


    @Override
    public void run(String... args) throws Exception {
        this.scheduleJobMapper.selectList(null).forEach(scheduleJobBean -> {
            try {
                CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJobBean.getId());
                if (cronTrigger == null) { // 如果不存在,则创建
                    ScheduleUtils.createScheduleJob(scheduler, scheduleJobBean);
                }else { // 如果存在,则更新
                    ScheduleUtils.updateScheduleJob(scheduler, scheduleJobBean);
                }
            } catch (Exception e) {
                log.error("创建定时任务失败", e);
            }
        });
    }
}
